package tomcat;

import servlet.HelloServlet;
import tomcat.annotation.Controller;
import tomcat.utils.PackageUtil;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 路由类
 */
public enum Router {
    // 使用 Enum 实现真正的单例模式
    INSTANCE;

    private final Map<String, Servlet> routeMap = new HashMap<>();

    Router() {
        loadServlets();
    }

    public static Router getInstance() {
        return Router.INSTANCE;
    }

    /**
     * 扫描所有 Servlet
     */
    private void loadServlets() {
        List<Class<?>> servlets = PackageUtil.getClasses("servlet", true);
        for (Class servletClass : servlets) {
//            System.out.println(servletClass.getName());
            for (Annotation annotation : servletClass.getAnnotations()) {
                // 判断是否加了 Controller 注解
                if (annotation instanceof Controller) {
                    try {
                        // 如果添加了 Controller 注解，则添加到路由map里
                        routeMap.put(((Controller) annotation).url(), (Servlet) servletClass.newInstance());
                    } catch (InstantiationException | IllegalAccessException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    public Map<String, Servlet> getRouteMap() {
        return routeMap;
    }
}
